<template>
  <a-row>
    <a-col :span="12">
      <div :style="containerStyle">
        <a-tree
          v-if="treeData.length > 0"
          :load-data="loadChildren"
          showIcon
          autoExpandParent
          :treeData="treeData"
          :selectedKeys="selectedKeys"
          v-model:expandedKeys="expandedKeys"
          @select="onSelect"
        >
          <template #title="{ title, key }">
            <FolderFilled style="color: #9e9e9e" /><span style="margin-left: 5px">{{ title }}</span>
          </template>
        </a-tree>
      </div>
    </a-col>
    <a-col :span="12" style="padding-left: 10px">
      <div :style="containerStyle">
        <user-list
          :multi="multi"
          :excludeUserIdList="excludeUserIdList"
          :dataList="userDataList"
          :selectedIdList="selectedIdList"
          @selected="onSelectUser"
          @un-select="unSelectUser"
        />
      </div>
    </a-col>
  </a-row>
</template>

<script lang="ts">
  import { defHttp } from "/@/utils/http/axios"
  import { computed, ref, watch, onMounted } from "vue"
  import UserList from "./UserList.vue"
  import { FolderFilled } from "@ant-design/icons-vue"
  import { Api } from "/@/api/url"

  export default {
    name: "DepartUserList",
    components: {
      UserList,
      FolderFilled,
    },
    props: {
      searchText: {
        type: String,
        default: "",
      },
      selectedIdList: {
        type: Array,
        default: () => [],
      },
      excludeUserIdList: {
        type: Array,
        default: () => [],
      },
      multi: {
        type: Boolean,
        default: false,
      },
    },
    emits: ["loaded", "selected", "unSelect"],
    setup(props, { emit }) {
      //export const queryById = (params) => defHttp.get({ url: Api.queryById, params }, { isTransformResponse: false });

      async function loadDepartTree(pid?) {
        const url = "/system-service/dept/listTreeSync"
        let params = {}
        if (pid) {
          params["pid"] = pid
        }
        const data = await defHttp.get({ url, params }, { isTransformResponse: false })
        console.log("loadDepartTree", data)
        return data
      }

      async function initRoot() {
        console.log("initRoot")
        const resp = await loadDepartTree()
        if (resp.success) {
          let arr = resp.data
          treeData.value = arr
          emitDepartOptions(arr)
        } else {
          console.error(resp.message)
        }
        clear()
      }

      function emitDepartOptions(arr) {
        let options = []
        if (arr && arr.length > 0) {
          options = arr.map((k) => {
            return {
              value: k.id,
              label: k.deptName,
            }
          })
        }
        emit("loaded", options)
      }

      initRoot()

      const treeData = ref<any[]>([])
      const selectedKeys = ref<string[]>([])
      const expandedKeys = ref<string[]>([])
      const selectedDeptId = ref("")
      function onSelect(ids, e) {
        console.log("------------", e)
        let record = e.node.dataRef
        selectedKeys.value = [record.key]
        selectedDeptId.value = record.id
        loadUserList()
      }

      function clear() {
        selectedDeptId.value = ""
      }
      async function loadChildren(treeNode) {
        console.log("loadChildren", treeNode)
        const resp = await loadDepartTree(treeNode.eventKey)
        if (resp.success) {
          let arr = resp.data
          treeNode.dataRef.children = [...arr]
          treeData.value = [...treeData.value]
        } else {
          console.error(resp.message)
        }
      }

      const maxHeight = ref(300)
      maxHeight.value = window.innerHeight - 300
      const containerStyle = computed(() => {
        return {
          "overflow-y": "auto",
          "max-height": maxHeight.value + "px",
        }
      })

      const userDataList = ref<any[]>([])
      async function loadUserList() {
        const url = Api.pageTenantUser
        let params = {
          pageNum: 1,
          pageSize: 10,
        }
        if (props.searchText) {
          params["keyword"] = props.searchText
        }
        console.log("selectedDeptId", selectedDeptId.value)
        params["deptId"] = selectedDeptId.value
        const resp = await defHttp.get({ url, params }, { isTransformResponse: false })
        if (resp.success) {
          const { records } = resp.data
          userDataList.value = records
        } else {
          console.error(resp.message)
        }
        console.log("depart-loadUserList", resp)
      }
      watch(
        () => props.searchText,
        () => {
          loadUserList()
        }
      )

      function onSelectUser(info) {
        emit("selected", info)
      }
      function unSelectUser(id) {
        emit("unSelect", id)
      }

      onMounted(() => {
        console.log("onMounted")
      })

      return {
        containerStyle,
        treeData,
        selectedKeys,
        expandedKeys,
        onSelect,
        loadChildren,
        onSelectUser,
        unSelectUser,
        userDataList,
      }
    },
  }
</script>

<style scoped></style>
